# -*- coding: utf-8 -*-
# @Time    : 2024/8/29 0:27
# @Author  : Alvin
# @File    : downloads.py


from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import Relationship


from app.models.base import Base, db


class Download(Base):
    __tablename__ = 'downloads'
    resources = Relationship('Resource', backref='downloads')
    user = Relationship('User', backref='downloads')
    download_id = Column(Integer, primary_key=True)
    resource_id = Column(Integer, ForeignKey('resources.resource_id'))
    user_id = Column(Integer, ForeignKey('users.id'))
    # download_time = Column(DateTime, default=datetime.utcnow)
    points_deducted = Column(Integer)  # 下载此次资源消耗的积分。

    @staticmethod
    def get_all_by_user_id(user_id):
        download_records = Download.query.filter_by(user_id=user_id).all()
        if not download_records:
            raise False
        return download_records

    @staticmethod
    def insert_download_record(uid, resource_id, points_deducted):
         with db.auto_commit():
             download_record = Download()
             download_record.user_id = uid
             download_record.resource_id = resource_id
             download_record.points_deducted = points_deducted
             db.session.add(download_record)